package com.mazihao.emos.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.mazihao.emos.db.dao.TbMeetingDao;
import com.mazihao.emos.db.dao.TbMessageDao;
import com.mazihao.emos.db.dao.TbUserDao;
import com.mazihao.emos.db.pojo.TbMeeting;
import com.mazihao.emos.exception.EmosException;
import com.mazihao.emos.service.MeetingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

/**
 * @author mazihao
 */
@Slf4j
@Service
public class MeetingServiceImpl implements MeetingService {
    @Resource
    private TbMeetingDao meetingDao;

    @Resource
    private TbUserDao userDao;

    private String code;

    @Override
    public void insertMeeting(TbMeeting meeting) {
        int rows = meetingDao.insertMeeting(meeting);
        if (rows > 0) {
            log.info("插入会议成功：{}", meeting);
        } else {
            throw new EmosException("会议添加失败！");
        }
        startMeetingWorkflow(meeting.getUuid(), meeting.getCreatorId().intValue(), meeting.getDate(), meeting.getStart());
    }

    @Override
    public ArrayList<HashMap<String, Object>> searchMeetingByPage(int userId) {
        ArrayList<HashMap<String, Object>> list = meetingDao.searchMeetingByPage(userId);
        String date = null;
        ArrayList<HashMap<String, Object>> resultList = new ArrayList<>();
        HashMap<String, Object> resultMap = null;
        JSONArray array = null;
        for (HashMap<String, Object> map : list) {
            String temp = map.get("date").toString();
            if (!temp.equals(date)) {
                date = temp;
                resultMap = new HashMap<>();
                resultMap.put("date", date);
                array = new JSONArray();
                resultMap.put("list", array);
                resultList.add(resultMap);
            }
            array.put(map);
        }
        return resultList;
    }

    private void startMeetingWorkflow(String uuid, int creatorId, String date, String start) {
        HashMap<String, Object> info = userDao.searchUserInfo(creatorId);
//        String[] roles = info.get("roles").toString().split(",");
//        if (!ArrayUtil.contains(roles, "总经理")) {
//            Integer managerId = userDao.searchDeptManagerId(creatorId);
//            Integer gmId = userDao.searchGmId();
//            boolean bool = meetingDao.searchMeetingMembersInSameDept(uuid);
//        }
        String instanceId = UUID.randomUUID().toString();
        HashMap<String,Object> params = new HashMap<>();
        params.put("uuid", uuid);
        params.put("instanceId", instanceId);
        int row = meetingDao.updateMeetingInstanceId(params);
        if (row != 1) {
            throw new EmosException("更新会议实例ID失败！");
        }
    }
}
